package com.codebox.wanandroid.module.hotkey.repository.remote;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;

import com.codebox.wanandroid.bean.HotKeyBean;
import com.codebox.wanandroid.http.RetrofitApi;
import com.codebox.wanandroid.module.hotkey.repository.HotKeyDataSource;
import com.codebox.wanandroid.module.hotkey.repository.local.LocalHotKeyDataSource;
import com.codebox.common.base.BaseResult;
import com.codebox.common.base.Resource;
import com.codebox.common.http.RetrofitFactory;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class RemoteHotKeyDataSource implements HotKeyDataSource {

    private static final RemoteHotKeyDataSource instance = new RemoteHotKeyDataSource();

    public RemoteHotKeyDataSource() {
    }

    public static RemoteHotKeyDataSource getInstance() {
        return instance;
    }

    private RetrofitApi api = RetrofitFactory.getInstance().create(RetrofitApi.class);

    @Override
    public LiveData<Resource<List<HotKeyBean>>> queryAll() {
        final MutableLiveData<Resource<List<HotKeyBean>>> liveData = new MutableLiveData<>();
        liveData.setValue(Resource.<List<HotKeyBean>>loading());
        api.getHotKey()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResult<List<HotKeyBean>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResult<List<HotKeyBean>> listBaseResult) {
                        liveData.setValue(Resource.response(listBaseResult));
                        LocalHotKeyDataSource.getInstance().addList(listBaseResult.getData());
                    }

                    @Override
                    public void onError(Throwable e) {
                        liveData.setValue(Resource.<List<HotKeyBean>>error(e));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
        return liveData;
    }
}
